﻿using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System.Linq;


namespace Meow.Core.Utils
{
    public static class ImgTools
    {
        public static float ColorToGray(Color color)
        {
            return (float)color.R / byte.MaxValue * 0.299f + (float)color.G / byte.MaxValue * 0.587f + (float)color.B / byte.MaxValue * 0.114f;
        }

        public static string ImageToSymbol(Texture2D image)
        {
            char[] codeLib = @"@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft|()1{}[]?-_+~<>i!lI;:,^`.  ".ToArray();
            int codeCount = codeLib.Length;
            string result = "";

            var gray = new float[image.Height * image.Width];
            var pixels = new Color[image.Height * image.Width];
            image.GetData<Color>(pixels);

            for(var i = 0; i < gray.Length; i ++)
            {
                gray[i] = ColorToGray(pixels[i]);
                gray[i] += MathHelper.Lerp(1f, 0f, (float)pixels[i].A / byte.MaxValue);
                gray[i] = MathHelper.Clamp(gray[i], 0f, 1f);
            }

            for (var y = 0; y < image.Height; y++)
            {
                for (var x = 0; x < image.Width; x++)
                {
                    result += codeLib[(int)((codeCount - 1) * gray[image.Width * y + x])];
                }
                result += "\r\n";
            }

            return result;
        }
    }
}
